package com.wewins.fota.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wewins.fota.bean.bo.TokenUserDetails;
import com.wewins.fota.bean.bo.filter.FilterCond;
import com.wewins.fota.bean.dto.PageReq;
import com.wewins.fota.bean.dto.PageRst;
import com.wewins.fota.bean.po.UserInfo;
import com.wewins.fota.mapper.UserInfoMapper;
import com.wewins.fota.sys.token.TokenManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserInfoService implements BasicService<TokenUserDetails, UserInfo> {
    private final UserInfoMapper userInfoMapper;
    private final RedisTemplate<String, String> template;
    private TokenManager manager;

    @Autowired
    public void setManager(TokenManager manager) {
        this.manager = manager;
    }

    @Autowired
    public UserInfoService(UserInfoMapper userInfoMapper, RedisTemplate<String, String> template) {
        this.userInfoMapper = userInfoMapper;
        this.template = template;
    }

    public TokenUserDetails getUserInfoByUsername(String username) {
        UserInfo userInfo = userInfoMapper.findByUsername(username);
        if (userInfo == null) {
            throw new UsernameNotFoundException("no user found");
        } else {
            return new TokenUserDetails(userInfo);
        }
    }

    @Override
    public <K extends FilterCond> PageRst<TokenUserDetails> queryAll(PageReq<K> pageReq) {
        PageHelper.startPage(pageReq);
        List<UserInfo> userInfos = userInfoMapper.queryAll();
        List<TokenUserDetails> list = userInfos.stream().map(TokenUserDetails::new).collect(Collectors.toList());
        return PageRst.<TokenUserDetails>builder().build().fillBy(PageInfo.of(list));
    }

    public TokenUserDetails findByToken(String token) {
        String username = manager.getUsernameFromToken(token);
        return this.getUserInfoByUsername(username);
    }

    @Override
    public TokenUserDetails findById(long id) {
        return new TokenUserDetails(userInfoMapper.findById((int) id));
    }

    @Override
    public TokenUserDetails insert(String username, UserInfo data) {
        return null;
    }

    @Override
    public Integer update(String username, UserInfo data) {
        return 0;
    }

    @Override
    public Integer deleteById(String username, long id) {
        return 0;
    }

    @Override
    public Integer delete(String username, UserInfo data) {
        return 0;
    }
}
